package com.zut.edu.nfc;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.zut.edu.R;
import com.zut.edu.bean.Product;
import com.zut.edu.http.BaseCallback;
import com.zut.edu.http.OkhttpHelper;
import com.zut.edu.utils.DESUtils;
import com.zut.edu.utils.StringUtils;
import com.zut.edu.utils.SystemTTSUtils;
import com.zut.edu.widget.CustomVideoView;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;


public class WriteTextActivity extends BaseNfcActivity implements View.OnClickListener{
    private String mText = "";
    private String update_url = "http://39.107.42.126:8088/product/update";
    private Tag detectedTag;
    private Product data;
    private String companyKey;
    private String lockStatus;
    private String volumeStatus;
    private String shockStatus;

    @BindView(R.id.stop_write_button)
    QMUIRoundButton stopwritebutton;
    @BindView(R.id.write_bg)
    CustomVideoView writebg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_writetext);
        ButterKnife.bind(this);
        initBackground();
        QMUIStatusBarHelper.translucent(this);//沉浸式
        setListener();
        RefreshData();
        companyKey = StringUtils.getLocalitem(this,"company","companyKey");
        lockStatus = StringUtils.getLocalString(this,"lock");
        volumeStatus = StringUtils.getLocalString(this,"volume");
        shockStatus = StringUtils.getLocalString(this,"shock");
    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //获取Tag对象
        detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        byte[] tagbytes = detectedTag.getId();    //获取16进制Tag的ID
        String mTagId = bytesToHexString(tagbytes);//16进制转字符串

        if(data!=null) {
            data.tagId = mTagId;
            data.productStatus = "1";
            mText = JSONObject.toJSONString(data);
            switch (lockStatus){
                case "0":
                    break;
                case "1":
                    mText = DESUtils.encode3DesBase64(mText.getBytes(),companyKey);
                    break;
                default:
            }

            Log.e("XXX",companyKey+" "+lockStatus+" "+mText.length());
        }
        else {
            Toast.makeText(WriteTextActivity.this, "已无更多数据", Toast.LENGTH_SHORT).show();
            RefreshData();
            return;
        }
        NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{createTextRecord(mText)});//写入mText
        boolean result = writeTag(ndefMessage, detectedTag);

        if (result) {
            Toast.makeText(WriteTextActivity.this, "写入成功", Toast.LENGTH_SHORT).show();
            updateProduct(update_url,data.getProductId(),mTagId);
            updateLock(mTagId,companyKey);
            switch (shockStatus){
                case "0":
                    break;
                case "1":
                    StringUtils.initShock(this);
                    break;
                default:
            }
            switch (volumeStatus){
                case "0":
                    break;
                case "1":
                    SystemTTSUtils systemTTSUtils = new SystemTTSUtils();
                    systemTTSUtils.initTTS(this,"写入成功");
                    break;
                default:
            }
            data =null;
            RefreshData();

        } else {
            Toast.makeText(WriteTextActivity.this, "写入失败", Toast.LENGTH_SHORT).show();
            RefreshData();
            switch (volumeStatus){
                case "0":
                    break;
                case "1":
                    SystemTTSUtils systemTTSUtils = new SystemTTSUtils();
                    systemTTSUtils.initTTS(this,"写入失败");
                    break;
                default:
            }
        }
    }

    /**
     * 创建NDEF文本数据
     *
     * @param text
     * @return
     */
    public static NdefRecord createTextRecord(String text) {
        byte[] langBytes = Locale.CHINA.getLanguage().getBytes(Charset.forName("US-ASCII"));
        Charset utfEncoding = Charset.forName("UTF-8");
        //将文本转换为UTF-8格式
        byte[] textBytes = text.getBytes(utfEncoding);
        //设置状态字节编码最高位数为0
        int utfBit = 0;
        //定义状态字节
        char status = (char) (utfBit + langBytes.length);
        byte[] data = new byte[1 + langBytes.length + textBytes.length];
        //设置第一个状态字节，先将状态码转换成字节
        data[0] = (byte) status;
        //设置语言编码，使用数组拷贝方法，从0开始拷贝到data中，拷贝到data的1到langBytes.length的位置
        System.arraycopy(langBytes, 0, data, 1, langBytes.length);
        //设置文本字节，使用数组拷贝方法，从0开始拷贝到data中，拷贝到data的1 + langBytes.length
        //到textBytes.length的位置
        System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
        //通过字节传入NdefRecord对象
        //NdefRecord.RTD_TEXT：传入类型 读写
        NdefRecord ndefRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
                NdefRecord.RTD_TEXT, new byte[0], data);
        return ndefRecord;
    }

    /**
     * 写数据
     *
     * @param ndefMessage 创建好的NDEF文本数据
     * @param tag         标签
     * @return
     */
    public static boolean writeTag(NdefMessage ndefMessage, Tag tag) {
        try {
            Ndef ndef = Ndef.get(tag);
            ndef.connect();
            ndef.writeNdefMessage(ndefMessage);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    public void setListener(){
        stopwritebutton.setOnClickListener(this);
        stopwritebutton.setChangeAlphaWhenPress(true);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.stop_write_button:
                super.onBackPressed();
                break;
        }
    }

    /**
     * 从服务器获取数据并写入
     * @return
     */
    public void RefreshData(){
        OkhttpHelper okhttpHelper = OkhttpHelper.getInstance();
        String companyId = StringUtils.getLocalitem(this,"company","companyId");
        Map<String,Object>params = new HashMap<>(1);
        params.put("id",companyId);
        okhttpHelper.get(StringUtils.BASE_URL+"/product/queryOne", params, new BaseCallback<Product>() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("F", String.valueOf(e));
            }

            @Override
            public void onSuccess(@NotNull Call call, @NotNull Response response, Product product, int code) throws IOException {

                switch (code){
                    case 0: data=product;
                    default:
                }
            }
            @Override
            public void onError(@NotNull Call call, @NotNull Response response, int code, Exception e) {
                if(e!=null)Log.e("E",String.valueOf(e));
            }
        });
    }
    /**
     * 加载背景
     */
    private void initBackground() {
        writebg.setVideoURI(Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.write_bg));

        //播放
        writebg.start();
        //循环播放
        writebg.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                writebg.start();
                mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(MediaPlayer mp, int what, int extra) {
                        return false;
                    }
                });
            }
        });

    }


    //返回视频背景重启加载
    @Override
    protected void onRestart() {
        super.onRestart();
        initBackground();
    }

    /**
     * 将16进制数据转字符串
     * @param src
     * @return
     */
    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.toUpperCase(Character.forDigit(
                    (src[i] >>> 4) & 0x0F, 16));
            buffer[1] = Character.toUpperCase(Character.forDigit(src[i] & 0x0F,
                    16));
            System.out.println(buffer);
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString();
    }

    private void updateProduct(String url,String productId,String tagId){
        OkhttpHelper okhttpHelper = OkhttpHelper.getInstance();

        Map<String,Object> params = new HashMap<>(3);
        params.put("productId", productId);
        params.put("tagId",tagId);
        params.put("productStatus","1");
        okhttpHelper.post(url, params, new BaseCallback<Product>() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("onFailure", String.valueOf(e));
            }

            @Override
            public void onSuccess(@NotNull Call call, @NotNull Response response, Product product, int code) throws IOException {
                Log.e("onSuccess", "response.code:"+response.code()+"\nresponse.message:"+response.message()+"\nresult.code:"+code);
            }


            @Override
            public void onError(@NotNull Call call, @NotNull Response response, int code, Exception e) {
                Log.e("onError", "response.code:"+response.code()+"\nresponse.message:"+response.message()+"\nresult.code:"+code);
            }
        });
    }
    private void updateLock(String tagId,String tagPassword){
        OkhttpHelper okhttpHelper = OkhttpHelper.getInstance();

        Map<String,Object> params = new HashMap<>(2);
        params.put("tagId",tagId);
        params.put("tagPassword",tagPassword);
        params.put("lockType",lockStatus);
        okhttpHelper.post(StringUtils.BASE_URL+"/lock/add", params, new BaseCallback<String>() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("onFailure", String.valueOf(e));
            }

            @Override
            public void onSuccess(@NotNull Call call, @NotNull Response response, String s, int code) throws IOException {
                Log.e("R2", response.message());
            }


            @Override
            public void onError(@NotNull Call call, @NotNull Response response, int code, Exception e) {
                Log.e("onError", "response.code:"+response.code()+"\nresponse.message:"+response.message()+"\nresult.code:"+code);
            }
        });
    }


}

